﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace ZhimeiSoft.Framework.Common.XmlUtils
{
    public class XmlHelper
    {
        private const string MagicText = "ab";
        private string strNameSpace;
        private string strPrefix;
        private XmlDocument document;
        private XmlNamespaceManager nameSpaceManager;

        public string Prefix
        {
            get { return this.strPrefix; }
        }

        public XmlDocument XmlDocument
        {
            get { return this.document; }
        }

        public XmlHelper(string strFileName)
        {
            if (!string.IsNullOrEmpty(strFileName))
            {
                this.document = this.LoadXmlFromFile(strFileName);
                this.strNameSpace = this.document.DocumentElement.NamespaceURI;
                if (!string.IsNullOrEmpty(this.strNameSpace))
                {
                    this.nameSpaceManager = new XmlNamespaceManager(this.document.NameTable);
                    this.nameSpaceManager.AddNamespace("ab", this.strNameSpace);
                    this.strPrefix = "ab";
                }
            }
        }

        public XmlDocument LoadXmlFromFile(string strFileName)
        {
            XmlDocument xmldoc;
            try
            {
                StreamReader streamReader = new StreamReader(strFileName);
                string xml = streamReader.ReadToEnd();
                streamReader.Close();
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xml);
                xmldoc = xmlDocument;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return xmldoc;
        }

        public string GetAttributeValue(string xpath, string attributeName)
        {
            XmlNode node = null;
            if (string.IsNullOrEmpty(this.strNameSpace))
                node = this.document.SelectSingleNode(xpath);
            else
                node = this.document.SelectSingleNode(xpath, this.nameSpaceManager);

            string result = string.Empty;
            if (node != null && node.Attributes[attributeName] != null)
                result = node.Attributes[attributeName].Value;

            return result;
        }

        public string GetNodeValue(string xpath)
        {
            XmlNode node = null;
            if (string.IsNullOrEmpty(this.strNameSpace))
                node = this.document.SelectSingleNode(xpath);
            else
                node = this.document.SelectSingleNode(xpath, this.nameSpaceManager);
            return node.InnerText;
        }
    }
}
